#ifndef _KC_TCPSERVER_H__KC_
#define _KC_TCPSERVER_H__KC_

#include <list>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include "../CommRequestHandler.h"
#include "../CommServer.h"
#include "../Connection.h"
#include "../../logs/Logger.h"

namespace kc_sf
{
	extern bool SERV_END;

	class TCPServer : public CommServer
	{
		public:

			TCPServer( int port, int max_connections, CommRequestHandler *client_handler );
			virtual ~TCPServer();

			virtual void startListening();
			virtual void stopListening();

			virtual std::list<int> getOpenConnectionSockets ();
			virtual void closeConnection( int client_sock );
			virtual void closeAllConnections ();

		protected:

			int tcp_port;
			int tcp_max_connections;

			int tcp_listening_socket;
		    bool tcp_is_listening;

		    std::list<Connection> tcp_clients;
			boost::thread_group tcp_client_threads;

		    boost::mutex tcp_listen_guard;
		    boost::mutex tcp_clients_guard;

		    CommRequestHandler *tcp_top_client_handler;

		    Logger tcp_logger;

		    void openListeningSocket();
		    virtual int acceptClient ();
		    void handleClient( Connection client_sock );
		    void interruptClientHandler( int client_sock ); // TODO
			void checkError(int err, const std::string &err_msg);
	};
}

#endif // _KC_TCPSERVER_H__KC_
